package top.soyask.bbs.service.imp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import org.apache.tomcat.util.codec.binary.Base64;

import top.soyask.bbs.dao.IFansDao;
import top.soyask.bbs.dao.IUserDao;
import top.soyask.bbs.dao.impl.FansDao;
import top.soyask.bbs.dao.impl.UserDao;
import top.soyask.bbs.domain.Fans;
import top.soyask.bbs.domain.User;
import top.soyask.bbs.service.IHandleService;

public class HandleService implements IHandleService {

	private IUserDao userDao = new UserDao();
	private IFansDao fansDao = new FansDao();

	@Override
	public String uploadPic(String base,String realPath) {

		String[] split = base.split(",");
		String filename = "imgs/default.png";
		if (split.length > 1) {
			filename = UUID.randomUUID().toString().replace("-", "");
			filename ="imgs/" + filename + ".png";
			File file = new File(realPath+filename);
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
				}
			}
			try {
				byte[] decode = Base64.decodeBase64(split[1]);
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(decode);
				fos.flush();
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return filename;
	}

	@Override
	public boolean regiser(User user) {
		try {
			userDao.save(user);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean login(long uid, String password) {
		return userDao.login(uid, password);
	}

	@Override
	public boolean updateInfo(User user) {
		try {
			userDao.update(user);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean follow(long uid, long targetId) {
		try {
			Fans fans = new Fans();
			fans.setFansId(uid);
			fans.setUid(targetId);
			fansDao.follow(fans, true);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean unFollow(long uid, int targetId) {
		try {
			Fans fans = new Fans();
			fans.setFansId(uid);
			fans.setUid(targetId);
			fansDao.follow(fans, false);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
